package com.jinyang.jetpackdemo.paging3

import android.app.Application
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.jinyang.jetpackdemo.AppHelper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import javax.inject.Singleton

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/8/18
 * @Description:
 */
@Database(entities = [RepoEntity::class], version = Constants.DB_VERSION)
abstract class AppDatabase : RoomDatabase() {
    abstract fun repoDao(): RepoDao

    companion object {
        val instance = AppDatabaseHolder.db
    }

    private object AppDatabaseHolder {
        val db: AppDatabase = Room
            .databaseBuilder(
                AppHelper.mContext,
                AppDatabase::class.java,
                Constants.DB_NAME
            )
            .allowMainThreadQueries() //允许在主线程中查询
            .build()
    }
}


@Module
@InstallIn(ApplicationComponent::class)
object RoomModule {
    @Provides
    @Singleton
    fun provideAppDatabase(application: Application): AppDatabase {
        return Room
            .databaseBuilder(
                application.applicationContext,
                AppDatabase::class.java,
                Constants.DB_NAME
            )
            .allowMainThreadQueries() //允许在主线程中查询
            .build()
    }

    @Provides
    @Singleton
    fun provideRepoDao(appDatabase: AppDatabase):RepoDao{
        return appDatabase.repoDao()
    }
}